package com.example.androidxdemo.adapter

import android.app.Activity
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.example.androidxdemo.R
import com.example.androidxdemo.database.AppDatabase
import com.example.androidxdemo.databinding.ItemRoomFunctionViewBinding
import com.example.androidxdemo.entity.Function


class RoomFunctionAdapter :
    BaseQuickAdapter<Function, BaseDataBindingHolder<ItemRoomFunctionViewBinding>>(R.layout.item_room_function_view) {

    lateinit var db: AppDatabase
    override fun convert(holder: BaseDataBindingHolder<ItemRoomFunctionViewBinding>, item: Function) {
        holder.dataBinding?.tvFunctionName?.setText(item.functionName)
        holder.dataBinding?.tvFunctionDes?.setText(item.functionDetail)

        holder.dataBinding?.btUpdate?.setOnClickListener {
            item.functionName = holder.dataBinding?.tvFunctionName?.text.toString()
            item.functionDetail = holder.dataBinding?.tvFunctionDes?.text.toString()
            Thread(Runnable {
                db.plantDao().update(item)
                val ac = context as Activity
                val list = db.plantDao().getFunctionList()
                ac.runOnUiThread { setList(list) }
                ToastUtils.showShort(context.getString(R.string.uptate_successful))
            }).start()
        }

        holder.dataBinding?.btDelete?.setOnClickListener {
            Thread(Runnable {
                db.plantDao().delete(item)
                val ac = context as Activity
                val list = db.plantDao().getFunctionList()
                ac.runOnUiThread { setList(list) }
                ToastUtils.showShort(context.getString(R.string.uptate_successful))
            }).start()
        }
    }

    fun setDB(db: AppDatabase) {
        this.db = db
    }
}